package com.project;

import com.project.config.WebMvcConfig;
import com.project.filter.CharFilter;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;


public class Boot7 {

    public Boot7(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();

        Context ctx = tomcat.addContext("",null);
        //注册监听器
        ctx.addApplicationListener("com.project.listener.ContextLis");
        ctx.addApplicationListener("com.project.listener.SessionLis");
        ctx.addApplicationListener("com.project.listener.SessionAttLis");

        this.registerFilter(ctx,new CharFilter(),"/*");


        WebApplicationContext wac = createApplicationContext(ctx.getServletContext());
        //创建前端控制器对象
        DispatcherServlet dis = new DispatcherServlet(wac);
        //注册前端控制器
        Wrapper wrp =  Tomcat.addServlet(ctx,"dis",dis);
        wrp.setLoadOnStartup(0);
        wrp.addMapping("/*");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册过滤器
     * @param ctx WEB上下文
     * @param filterObj 过滤器对象
     * @param urlPattern 过滤范围
     */
    private void registerFilter(Context ctx, Filter filterObj, String urlPattern){
        FilterDef fd = new FilterDef();
        //设置过滤器
        fd.setFilter(filterObj);
        //设置过滤器名称
        fd.setFilterName(filterObj.getClass().getName());

        FilterMap fm = new FilterMap();
        //设置过滤器名称，必须和FilterDef中的名称一致
        fm.setFilterName(filterObj.getClass().getName());
        //设置过滤器过滤范围
        fm.addURLPattern(urlPattern);

        //注册过滤器
        ctx.addFilterDef(fd);
        ctx.addFilterMap(fm);
    }

    /**
     * 创建springMVC应用上下文
     * @param servletContext
     * @return
     */
    public  WebApplicationContext createApplicationContext(
            ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    public static void main(String[] args) {
        new Boot7();
    }
}
